package com.ctshk.rpc.payment.strategy.impl;

import com.ctshk.rpc.payment.dto.UnionPayConfig;
import com.ctshk.rpc.payment.dto.req.unionpay.UnionPayTransReq;
import com.ctshk.rpc.payment.req.PayCommonReq;
import com.ctshk.rpc.payment.utils.unionpay.UnionPayConstant;
import com.ctshk.rpc.payment.utils.unionpay.UnionPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @BelongsProject: ctshk-cloud
 * @BelongsPackage: com.ctshk.rpc.payment.strategy.impl
 * @Author: hef
 * @CreateTime: 2021-04-26 11:48
 * @Description: 银联支付
 */
@Slf4j
@Component
public class UnionPayAppStrategy extends UnionPayStrategy {

    /**
     * 接口地址
     */
    private static final String API_ADDR = "/gateway/api/appTransReq.do";

    @Override
    public String pay(PayCommonReq req) {
        UnionPayConfig config = getConfig();
        //封装请求参数
        UnionPayTransReq unionPayApiAlterableReq = new UnionPayTransReq(
                "08", config.getCallbackUrl(), config.getMerId(),
                String.valueOf(req.getOrderId()), LocalDateTime.now(),
                req.getTotalFee(), "156",config.getFrontUrl());
        Map<String, Object> data = unionPayApiAlterableReq.toMap();
        Map<String, String> submitFromData = UnionPayUtil.signData(data);
        Map<String, String> resmap = UnionPayUtil.submitUrl(submitFromData, config.getRequestHostUrl() + API_ADDR);
        log.debug("union resmap:{}", resmap.toString());
        if (StringUtils.isNotBlank(resmap.get(UnionPayConstant.RESP_CODE_KEY)) &&
                UnionPayConstant.RESP_CODE_SUCCESS.equals(resmap.get(UnionPayConstant.RESP_CODE_KEY))) {
            //商户推送订单后银联移动支付系统返回该流水号，商户调用支付控件时使用
            return resmap.get("tn");
        } else {
            return null;
        }
    }
}
